package cn.xinfei.xdecision.data.core.frame.listener;

import cn.xinfei.xdecision.common.model.datax.consts.VariableConst;
import cn.xinfei.xdecision.common.model.datax.enums.ExecutorSceneEnum;
import cn.xinfei.xdecision.data.core.vo.VarDatasourceDTO;
import cn.xinfei.xdecision.data.service.VarDataSourceCallLogService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class VarDataSourceLogSaveListener {
    @Autowired
    VarDataSourceCallLogService varDataSourceCallLogService;

    @Async
    @EventListener
    @Retryable(value = Exception.class, maxAttempts = 2, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public void onBatchSaveVarLogEvent(VarDataSourceLogEvent VarDataSourceLogEvent) {
        VarDatasourceDTO saveVarDataSourceDTO = VarDataSourceLogEvent.getData();
        MDC.put(VariableConst.HANDLE_NAME, ExecutorSceneEnum.LOGGER.name());
        MDC.put(VariableConst.COLLECT_STAGE, saveVarDataSourceDTO.getCollectStage());
        if (Objects.isNull(saveVarDataSourceDTO.getVarDataSourceCallLog())) {
            log.info("requestId: {} 无变量DataSource日志需要插入", saveVarDataSourceDTO.getRequestId());
        } else {
            varDataSourceCallLogService.insert(saveVarDataSourceDTO.getVarDataSourceCallLog());
            log.info("requestId: {}  变量DataSource日志异步记录成功!",
                    saveVarDataSourceDTO.getRequestId());
        }
        MDC.clear();
    }
}
